from flask import Flask, render_template, jsonify
from datetime import datetime
import sqlite3
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config_loader import ConfigLoader

# 获取配置文件路径
config_path = os.environ.get('DAYCHECK_CONFIG', '../config.yaml')
config = ConfigLoader(config_path)
db_config = config.get_database_config()
status_db_path = db_config['status_db']

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

# 数据库初始化
def init_db():
    conn = sqlite3.connect(status_db_path)
    c = conn.cursor()
    c.execute('''
            CREATE TABLE IF NOT EXISTS current_status (
                db_name TEXT PRIMARY KEY,
                status TEXT NOT NULL,
                last_check_time DATETIME NOT NULL,
                details TEXT
            )''')
    c.execute('''
            CREATE TABLE IF NOT EXISTS status_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                db_name TEXT NOT NULL,
                status TEXT NOT NULL,
                check_time DATETIME NOT NULL,
                details TEXT
            )''')
    conn.commit()
    conn.close()

@app.route('/api/status')
def get_status():
    conn = sqlite3.connect(status_db_path)
    c = conn.cursor()
    c.execute("""
        SELECT db_name, status, last_check_time, details 
        FROM current_status
    """)
    records = c.fetchall()
    data = [
        {
            'db_name': r[0],
            'status': 'Failed' if r[1] == 'Failed' else 'Normal',
            'check_time': r[2],
            'details': r[3] or ''
        } for r in records
    ]
    conn.close()
    return jsonify({'data': data})

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/history')
def history():
    conn = sqlite3.connect(status_db_path)
    c = conn.cursor()
    c.execute('SELECT db_name, status, check_time, details FROM status_history ORDER BY check_time DESC LIMIT 100')
    records = c.fetchall()
    return render_template('history.html', records=records)

@app.route('/failures')
def failures():
    conn = sqlite3.connect(status_db_path)
    c = conn.cursor()
    c.execute("""
        SELECT h.db_name, h.status, h.check_time, h.details 
        FROM status_history h
        JOIN current_status c ON h.db_name = c.db_name
        WHERE h.status = 'Failed'
        ORDER BY h.check_time DESC 
        LIMIT 50
    """)
    records = c.fetchall()
    conn.close()
    return render_template('failures.html', records=records)

if __name__ == '__main__':
    init_db()
    app.run(host='0.0.0.0', port=5000, debug=False)